package com.bflow.web.controller;

import com.bflow.commons.exception.BizException;
import com.bflow.util.DateUtils;
import com.bflow.util.JsonUtil;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Name 基础Controller
 * @Author haowen
 * @Date 2019-01-03
 */
public class BflowBaseController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected final int STATUS_OK = 200;
    protected final int STATUS_ERROR = 500;

    protected String returnJson(int statusCode, Object obj, String message){
        Map<String, Object> result = new HashMap<String, Object>(3);
        result.put("statusCode", statusCode);
        result.put("data", obj);
        result.put("message", message);
        System.err.println(JsonUtil.toStr(result));
        return JsonUtil.toStr(result);
    }

    protected String returnOk(Object obj, String message){
        return returnJson(STATUS_OK, obj, message);
    }

    protected String returnOk(String message){
        return returnJson(STATUS_OK, null, message);
    }

    protected String returnFail(String message){
        return returnJson(STATUS_ERROR, null, message);
    }

    protected String returnFail(Object obj, String message){
        return returnJson(STATUS_ERROR, obj, message);
    }

    protected String returnFail(Exception e, String defMess){
        logger.error(defMess, e);
        if(e instanceof BizException)
            defMess = e.getMessage();
        return returnJson(STATUS_ERROR, null, defMess);
    }

//
//    /**
//     * 设置请求分页数据
//     */
//    protected void startPage()
//    {
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        Integer pageNum = pageDomain.getPageNum();
//        Integer pageSize = pageDomain.getPageSize();
//        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
//        {
//            String orderBy = pageDomain.getOrderBy();
//            PageHelper.startPage(pageNum, pageSize, orderBy);
//        }
//    }
//
//    /**
//     * 响应请求分页数据
//     */
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//    protected TableDataInfo getDataTable(List<?> list)
//    {
//        TableDataInfo rspData = new TableDataInfo();
//        rspData.setCode(0);
//        rspData.setRows(list);
//        rspData.setTotal(new PageInfo(list).getTotal());
//        return rspData;
//    }



    /**
     * 初始化数据绑定
     * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击
     * 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                try {
//                    Date date = DateUtils.parseDate(text, "");
                    Date date = DateUtils.parseDate(text);
                    setValue(date);
                } catch (Exception e) {
                    logger.error(text+" 日期解析失败,格式有误", e);
                }
            }
        });
    }

}
